package com.douyuehan.doubao.project.controller;

import com.douyuehan.doubao.common.api.ApiResult;
import com.douyuehan.doubao.project.model.dto.LoginDTO;
import com.douyuehan.doubao.project.model.dto.RegisterDTO;
import com.douyuehan.doubao.project.model.entity.BmsUser;
import com.douyuehan.doubao.project.service.BmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

import static com.douyuehan.doubao.jwt.JwtUtil.USER_NAME;

@RestController
@RequestMapping("bms/user")
public class BmsUserController extends BaseController{

    @Autowired
    private BmsUserService bmsUserService;

    @PostMapping("/register")
    public ApiResult<Map<String,Object>> userRegister(@Valid @RequestBody RegisterDTO registerDTO){
        BmsUser bmsUser = bmsUserService.userRegister(registerDTO);
        if(ObjectUtils.isEmpty(bmsUser)){
            return ApiResult.failed("账号注册失败");
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("user", bmsUser);
        return ApiResult.success(map);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ApiResult<Map<String, String>> login(@Valid @RequestBody LoginDTO dto) {
        String token = bmsUserService.executeLogin(dto);
        if (ObjectUtils.isEmpty(token)) {
            return ApiResult.failed("账号密码错误");
        }
        Map<String, String> map = new HashMap<>(16);
        map.put("token", token);
        return ApiResult.success(map, "登录成功");
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    //从请求对象的请求头里获取userName属性
    public ApiResult<BmsUser> getUser(@RequestHeader(value = USER_NAME) String userName) {
        BmsUser user = bmsUserService.getUserByUsername(userName);
        return ApiResult.success(user);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ApiResult<Object> logOut() {
        return ApiResult.success(null, "注销成功");
    }

}
